package ynu.edu.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import ynu.edu.common.entity.LogicEntity;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static ynu.edu.entity.Order.ORDER_STATE_PAID;

@Entity
@Getter
@Setter
//@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Shop extends LogicEntity {
    @Column
    private String shopName;
    @Column
    private String shopDescription;
    @Lob
    @Basic(fetch = FetchType.LAZY)
    @Column(name="shopImage", columnDefinition="longblob", nullable=true)
    private String shopImage;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "business_id")
    @JsonIgnoreProperties("shops")
    private Business business;

    @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER,orphanRemoval = true)
    @JoinColumn(name = "shop_id")
    @JsonIgnoreProperties("shop")
    private Set<ShopItem> shopItems;

    @OneToMany(cascade = {CascadeType.MERGE,CascadeType.REMOVE},fetch = FetchType.EAGER)
    @JoinColumn(name = "shop_id")
    @JsonIgnoreProperties("shop")
    private Set<Order> orders;

    @JsonIgnore
    public List<ShopItem> listMyShopItems(){
        return new ArrayList<>(this.shopItems);
    }

    @JsonIgnore
    public ShopItem createShopItem(Item item,Double price){
        ShopItem shopItem = new ShopItem();
        shopItem.setShop(this);
        shopItem.setShopItemPrice(price);
        shopItem.setItem(item);
        shopItems.add(shopItem);
        return shopItem;
    }

    @JsonIgnore
    public void updateShopItem(ShopItem shopItem){
        //判断该商品是否在我的商店中
        if(shopItems.contains(shopItem)){
            shopItem.setIsOnShelves(shopItem.getIsOnShelves()==0?1:0);
        }
    }

    @JsonIgnore
    public List<ShopItem> listMyShopItemsIsOnShelves(){
        //获取已经上架的商品
        return this.shopItems.stream().filter(shopItem -> shopItem.getIsOnShelves() == 0).collect(Collectors.toList());
    }

    @JsonIgnore
    public List<Order> listMyOrders(Integer orderState){
        if (orderState.equals(ORDER_STATE_PAID)){
            return  getOrders().stream().filter(order -> order.getIsDeleted() == 0).collect(Collectors.toList());
        }
        return  getOrders().stream().filter(order -> order.getIsDeleted() == 0
                && Objects.equals(order.getOrderState(), orderState)).collect(Collectors.toList());
    }

    @JsonIgnore
    public Order updateOrderState(Order order,Integer orderState){
        if (orders.contains(order)&& Objects.equals(order.getOrderState(), ORDER_STATE_PAID)){
            order.setOrderState(orderState);
            return order;
        }
        return null;
    }
}
